
import { List, Collapse, Space, Button, Popconfirm } from "antd";
import styles from './index.module.less';
import Controller from 'Controller'
import React from "react";
import BaseProperties from "./panels/BaseProperties";
import TypeProperties from "./panels/TypeProperties";
import { DeleteOutlined } from "@ant-design/icons";

const { Panel } = Collapse;

export default function PanelSceneElement() {

    const threeController = Controller.instance.useMemo(s => s.threeController, []);

    const uuids = threeController.useMemo(s => {
        if (!s.scene) return [];
        return s.scene.children.filter(e => s.elementMap.has(e.uuid)).map(e => e.uuid);
    }, [])

    return (
        <div className={styles.panelSceneElement} >
            <Collapse defaultActiveKey={['1', '2']}>
                <Panel header="场景原件" key="1">
                    <List
                        className={styles.list}
                        bordered
                        dataSource={uuids}
                        renderItem={item => <Element uuid={item} />}
                    />
                </Panel>
                <Panel header="原件属性" key="2">
                    <Space direction="vertical" style={{ width: '100%' }}>
                        <BaseProperties />
                        <TypeProperties />
                    </Space>
                </Panel>
            </Collapse>
        </div>
    )
}

function Element(props: { uuid: string }) {

    const threeController = Controller.instance.useMemo(s => s.threeController, []);

    const selectedElementUuid = threeController.useMemo(s => s.selectedElementUuid, []);

    const elementMap = threeController.useMemo(s => s.elementMap, []);

    const element = React.useMemo(() => elementMap.get(props.uuid), [elementMap, props.uuid])

    const onClick = React.useCallback(() => {
        threeController.pipeline(async s => {
            s.selectedElementUuid = props.uuid
        })()
    }, [props.uuid, threeController])

    if (!element) return <></>;

    return (
        <List.Item
            onClick={onClick}
            className={`${styles.listItem} ${selectedElementUuid === props.uuid ? styles.elementSelected : ''}`}
            actions={[<DeleteItemButton uuid={props.uuid} />]}
        >
            {element.object3D.name || element.object3D.uuid}
        </List.Item>
    )
}

function DeleteItemButton(props: { uuid: string }) {

    const threeController = Controller.instance.useMemo(s => s.threeController, []);

    const onConfirm = React.useCallback(() => { threeController.sceneRem(props.uuid) }, [props.uuid, threeController]);

    return (
        <Popconfirm
            title="你确定要删除这个元素"
            onConfirm={onConfirm}
        >
            <Button type="link"><DeleteOutlined /></Button>
        </Popconfirm>
    )
}